
/*
 * @(#)MaintDmsCheckinAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.dms.dao.DmsVersionDAObject;
import com.dcivision.dms.web.MaintDmsVersionForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;

/**
  MaintDmsCheckinAction.java

  This class is for maint dms check in file in workflow step.

    @author          Tony Chen
    @company         DCIVision Limited
    @creation date   16/11/2004
    @version         $Revision: 1.10 $
*/

public class MaintDmsCheckinAction extends com.dcivision.framework.web.AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.10 $";


  /** Creates a new instance of MaintWorkflowStepAction */
  public MaintDmsCheckinAction() {
    super();
  }

  /** getFunctionCode
   *
   * Abstract function which sub-class should implement to return the corresponding
   * function code.
   *
   * @return   The function code
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.WORKFLOW_TASK);
  }

  /** getMajorDAOClassName
   *
   * Abstract function which sub-class should implement to return the corresponding
   * major DAO class name used in this class.
   *
   * @return   The DAO class name
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.workflow.dao.WorkflowStepDAObject");
  }


  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {

    MaintDmsVersionForm maintForm = (MaintDmsVersionForm)form;
    String opMode = maintForm.getOpMode();
    String navMode = maintForm.getNavMode();
    if(Utility.isEmpty(navMode)){
      navMode = request.getParameter("navMode");
    }

    if(GlobalConstant.NAV_MODE_NEW.equals(navMode)){
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      Connection conn = this.getConnection(request);
      SessionContainer sessionCon = this.getSessionContainer(request);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionCon, conn);
      VersionControlManager versionControlManager = new VersionControlManager(sessionCon, conn);
      DmsVersionDAObject versionDAO = new DmsVersionDAObject(sessionCon, conn);

      String documentID = maintForm.getDocumentID();
      String parentID = maintForm.getParentID();
      String rootID = maintForm.getRootID();
      String directURL = maintForm.getDirectURL();
      String checkinType = maintForm.getCheckinType();
      String referenceNo = maintForm.getReferenceNo();
      String description = maintForm.getDescription();

      //Check out the document first
      DmsDocument document = docRetrievalManager.getDocument(new Integer(documentID));
      //bill add for EIP-1454 start
      if(!DmsVersion.EXCLUSIVE_LOCK.equals(document.getItemStatus())){
        versionControlManager.checkoutDocument(DmsVersion.EXCLUSIVE_LOCK, document);
      }
      //bill add for EIP-1454 end
      log.debug("document checked out");
      
      //for in dms audit trail ,the check out must be before check in.
      long waitTime = 500;
      try{
        Thread.sleep(waitTime);
      }catch(Exception e){}
      
      try {
        if(DmsOperationConstant.CREATE_NEW_CHECKIN.equals(checkinType) ||
            DmsOperationConstant.CREATE_MINOR_CHECKIN.equals(checkinType) ){
          DmsVersion newVersion = null;
          InputStream inputStream = null;
          try {
            inputStream = maintForm.getUploadFile().getInputStream();
          }catch(FileNotFoundException fnfe){
            throw new ApplicationException(ErrorConstant.FORM_UPLOAD_FILE_FAIL);
          }catch(IOException ioe){
            throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR);
          }

          DmsVersion version = new DmsVersion();
          version.setReferenceNo(referenceNo);
          version.setDescription(description);
          version.setItemSize(new Integer(maintForm.getUploadFile().getFileSize()) );
          version.setDocumentID(new Integer(documentID));
          version.setCheckinFileName(maintForm.getUploadFile().getFileName());
          
          //check in file with Major
          if ( DmsOperationConstant.CREATE_NEW_CHECKIN.equals(checkinType) ) {
            version.setParentID(new Integer(0));
          } else {
            DmsVersion latestVersion = version;
            List versionList = versionDAO.getParentVersionsListByParentIDByDocumentID(new Integer(0), new Integer(documentID)); //first level
            if (versionList.size() > 0) {
              latestVersion = (DmsVersion)versionList.get(0);
            }
            if (latestVersion.getParentID().intValue() == 0){
              version.setParentID(latestVersion.getID());
            }else{
              version.setParentID(latestVersion.getParentID());
            }           
          }
          newVersion = versionControlManager.checkinDocument(true, checkinType, new Integer(documentID), version, inputStream);
        } else {
          //unlock the document as there is no update
          versionControlManager.unlockDocumentForNoUpdateCheckin(new Integer(documentID));
        }
      }
      catch (ApplicationException appEx) {
        this.rollback(request);
        this.handleApplicationException(request, appEx);
      }
      
      if (isError(request)) {
        maintForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
      }
      
      log.debug("document checked in");
      this.commit(request);
      if(!Utility.isEmpty(directURL)){
        directURL = TextUtility.replaceString(directURL,"|","&");
        try {
          response.sendRedirect(directURL);
        } catch (IOException ioex){
          log.error("URL not found: " + ioex.toString());
        }
        return null;
      }

    }

    return super.execute(mapping,form,request,response);
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {

  }

}
